package com.centerm.structure.service.impl;

import java.io.File;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.centerm.common.constant.Constant;
import com.centerm.common.exception.MyRuntimeException;
import com.centerm.common.util.UserPasswordCrypter;
import com.centerm.common.view.page.PageQueryResult;
import com.centerm.structure.dao.DepartmentDao;
import com.centerm.structure.dao.UserDao;
import com.centerm.structure.dao.UserRoleDao;
import com.centerm.structure.domain.Department;
import com.centerm.structure.domain.User;
import com.centerm.structure.dto.UserInfo;
import com.centerm.structure.service.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

/**
 * 
 * @ClassName: UserServiceImpl
 * @Description: 用户服务实现类
 * @author czy
 * @date 2017年8月10日
 */
@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserDao userDao;
	@Autowired
	private UserRoleDao userRoleDao;
	@Autowired
	private DepartmentDao departmentDao;

	@Override
	public List<User> listAllName() {
		return userDao.listAllName();
	}

	@Override
	public List<User> listByIds(String ids) {
		return userDao.listByIds(ids.split(","));
	}

	@Override
	public List<User> listByParam(UserInfo userInfo) {
		// 对密码加密
		String password = userInfo.getPassword();
		if (StringUtils.isNotBlank(password)) {
			userInfo.setPassword(UserPasswordCrypter.crypt(password));
		}
		List<User> list = userDao.listByParam(userInfo);
		return list;
	}

	@Override
	public Boolean existUid(String uid) {
		if (StringUtils.isBlank(uid)) {
			throw new MyRuntimeException("uid不能为空！");
		}
		UserInfo userInfo = new UserInfo();
		userInfo.setUid(uid);
		List<User> list = userDao.listByParam(userInfo);
		return list.size() > 0 ? true : false;
	}

	@Override
	public PageQueryResult<UserInfo> pageUserInfoList(Integer pageNum,
			Integer pageSize, UserInfo userInfo, List<Integer> departmentIdList) {
		Page<UserInfo> page = PageHelper.startPage(pageNum, pageSize);
		userInfo.setDepartment(null);
		List<UserInfo> list = userDao.listUserInfoByParam(userInfo,
				departmentIdList);
		PageQueryResult<UserInfo> resultInfo = new PageQueryResult<UserInfo>(
				page, list);
		return resultInfo;
	}

	@Override
	@Transactional
	public Integer insert(UserInfo userInfo) {
		User user = convertRequest(userInfo);
		if (existUid(user.getUid())) {
			String errorMsg = "新增失败，用户帐号已存在!";
			throw new MyRuntimeException(errorMsg);
		}
		// 新增记录必定有效
		user.setValid(1);

		// 头像可不上传 先修改头像路径为真实路径
		String realFilePath = null;
		File file = null;
		if (user.getHeadImage() != null) {
			file = new File(user.getHeadImage());
			String fname = file.getName();
			String suffix = fname.contains(".") ? fname.substring(fname
					.indexOf(".")) : "";
			realFilePath = Constant.HEADIMAGEPATH + userInfo.getUid() + suffix;
			user.setHeadImage(realFilePath);
		} else {
			// TODO 默认头像
			user.setHeadImage("");
		}

		Integer result = userDao.insert(user);
		if (result != 1) {
			String errorMsg = "新增用户错误，请排查!";
			throw new MyRuntimeException(errorMsg);
		}

		// 新增成功后才将文件真正转移到真实路径
		if (file != null) {
			if (!file.renameTo(new File(realFilePath))) {
				String errorMsg = "新增用户信息时移动头像图片错误，请排查！";
				throw new MyRuntimeException(errorMsg);
			}
		}
		return user.getId();
	}

	@Override
	public Integer update(UserInfo userInfo) {
		User user = convertRequest(userInfo);
		if (StringUtils.isNotBlank(user.getUid())) {
			String errorMsg = "更新用户错误，用户帐号不允许修改!";
			throw new MyRuntimeException(errorMsg);
		}
		Integer result = userDao.update(user);
		if (StringUtils.isNoneBlank(userInfo.getHeadImage())) {
			// 如果头像不为空，则说明是更改头像
			File file = new File(user.getHeadImage());
			User newUser = userDao.getById(userInfo.getId());
			String realFilePath = Constant.HEADIMAGEPATH
					+ newUser.getHeadImage();
			// 修改成功后将文件真正转移到真实路径
			if (!file.renameTo(new File(realFilePath))) {
				String errorMsg = "更新用户信息时移动头像图片错误，请排查！";
				throw new MyRuntimeException(errorMsg);
			}
		}
		if (result != 1) {
			String errorMsg = "更新用户错误，请排查!";
			throw new MyRuntimeException(errorMsg);
		}
		return result;
	}

	@Override
	@Transactional
	public Integer delete(Integer id) {
		// 物理删除人员时应当把人员角色信息也删除
		Integer result = userRoleDao.deleteByUserId(id);
		if (result < 1) {
			String errorMsg = "删除用户角色关联关系错误，请排查!";
			throw new MyRuntimeException(errorMsg);
		}
		// 最后正式删除用户
		result = userDao.deleteById(id);
		if (result != 1) {
			String errorMsg = "删除用户错误，请排查!";
			throw new MyRuntimeException(errorMsg);
		}
		return result;
	}

	private User convertRequest(UserInfo userInfo) {
		// 对密码加密
		String password = userInfo.getPassword();
		if (StringUtils.isNoneBlank(password)) {
			userInfo.setPassword(UserPasswordCrypter.crypt(password));
		}
		// TODO czy 该转换方法并不正式，存在风险
		return JSON.parseObject(JSON.toJSONString(userInfo), User.class);
	}

	@Override
	public UserInfo getUserInfoById(Integer id) {
		return userDao.getUserInfoById(id);
	}

	@Override
	public Integer updatePassWord(UserInfo userInfo) {
		User user = new User();
		user.setId(userInfo.getId());
		user.setPassword(UserPasswordCrypter.crypt(userInfo.getPassword()));
		return userDao.update(user);
	}

	@Override
	public Integer deleteUserDeparment(UserInfo userInfo) {
		User user = userDao.getById(userInfo.getId());
		Department department = departmentDao.getById(user.getDepartment());
		if (department.getParentId() != null) {
			user.setDepartment(department.getParentId());
		}
		if (department.getManager().intValue() == user.getId().intValue()) {
			// TODO 部门无负债人时使用0
			department.setManager(0);
			departmentDao.update(department);
		}
		return userDao.update(user);
	}

	@Override
	public List<UserInfo> listDepartmentMember(UserInfo userInfo,
			List<Integer> departmentIdList) {
		//TODO 防止为空跳到等于判断中
		if (departmentIdList != null) {
			userInfo.setDepartment(null);
		}
		return userDao.listUserInfoByParam(userInfo, departmentIdList);
	}
}
